package com.xiweicheng.test.proxy.doc.handler;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.xiweicheng.test.proxy.Constants;
import com.xiweicheng.test.proxy.Utils;

public class ADocHandler implements IDocHandler {

	@Override
	public void handle(Document doc, String baseUrl, String basePath) {
		Elements links = doc.select("a[href]");
		links.forEach(e -> {

			String href = e.attr("href").trim();

			if (href.matches("^(\\s*http[s]?://).*")) {
				// http://www.pingan.com/homepage/contact.shtml?k=v =>
				// /?target=http://www.pingan.com/homepage/contact.shtml?k=v
				StringBuffer sb = new StringBuffer();
				try {
					String encodeHref = URLEncoder.encode(e.attr("href").trim(), "utf-8");
					sb.append("/").append("?").append(Constants.TARGET_NAME).append("=").append(encodeHref);
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}

				e.attr("href", sb.toString());
			} else {
				// /contact.shtml?k=v =>
				// /?target=http://www.pingan.com/contact.shtml?k=v
				StringBuffer sb = new StringBuffer();
				try {

					String _href = null;

					if (href.startsWith("javascript:")) {
						return;
					} else if (href.startsWith("#")) {
						return;
					} else if (href.startsWith("//")) {
						try {
							_href = new URL(baseUrl).getProtocol() + ":" + e.attr("href").trim();
						} catch (MalformedURLException e1) {
							e1.printStackTrace();
						}
					} else if (!href.startsWith("/")) {
						_href = Utils.joinPaths(baseUrl, Utils.getBasePath(basePath), e.attr("href").trim());
					} else {
						_href = Utils.joinPaths(baseUrl, e.attr("href").trim());
					}
					String encodeHref = URLEncoder.encode(_href, "utf-8");
					sb.append("/").append("?").append(Constants.TARGET_NAME).append("=").append(encodeHref);
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}

				e.attr("href", sb.toString());
			}

		});
	}

}
